//作者：唐源江

const express = require("express");
const db = require("../model/db");
const router = express.Router();
const User = db.User;
const crypto = require("crypto")//引用加密模块

//登录
//作者：唐源江
router.post("/login", async function (req, res) {
    const md5 = crypto.createHash("md5");
    const u = await User.findOne({ mobile: req.body.mobile, pwd: md5.update(req.body.pwd).digest("hex") });
    if (u) {
        res.cookie("userId", u._id.toString(), {
            signed: true
        });
        res.send(u);
    } else {
        res.send(false);
    }
})

//添加
//作者：唐源江
router.post("/zhuce", async function (req, res) {
    const u= await User.findOne({
        mobile:req.body.mobile
    })
    if(u){
        res.send(false);
        return;
    }
    const md5 = crypto.createHash("md5");
    req.body.pwd = md5.update(req.body.pwd).digest("hex");
    await User.create(req.body);
    res.send(true);
})

//删除
//作者：唐源江
router.delete("/:id", async function (req, res) {
    await User.deleteOne({
        _id: req.params.id
    })
    res.send(true);

})

//查询
//作者：唐源江
// router.get("/:mobile", async function(req, res) {
//     const data = await User.find({mobile: req.params.mobile});
//     res.send({
//         code: 0,
//         msg: "",
//         data: data
//     });
// });
router.get("/all", async function (req, res) {
    let condition = {};
    if (req.query.key) {
        let exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询正则表达式
        condition = {
            $or: [
                { mobile: { $regex: exp } },
                { pwd: { $regex: exp } }
            ]
        }
    }
    const data = await User.find(condition);
    res.send({
        code: 0,
        msg: "",
        count: await User.countDocuments(condition),
        data: data
    });
})

//根据ID查询
//作者：唐源江
router.get("/:id", async function (req, res) {
    const data = await User.findById(req.params.id);
    res.send(data);
})

//修改用户
//作者 唐源江
router.put("/:id", async (req, res) => {
    const md5 = crypto.createHash("md5");
    req.body.pwd = md5.update(req.body.pwd).digest("hex");
    const data = await db.User.updateOne({
        _id: req.params.id
    }, {
        mobile: req.body.mobile,
        pwd: req.body.pwd,
        isAdmin: req.body.isAdmin
    })
    res.send({
        code: 0,
        message: "",
        data
    });
})

module.exports = router;